<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types = 1);

namespace app\index\model;

use app\SearchModel;
use think\Exception;
use app\command\Group;
use think\facade\Db;

class Collage extends BaseModel
{
    protected $globalScope = ['mallId'];

    public function collageItem()
    {
        return $this->hasMany(CollageItem::class, 'collage_id', 'id');
    }

    public function commodity()
    {
        return $this->hasOne(Commodity::class, 'id', 'commodity_id');
    }

    public function groupCommodity()
    {
        return $this->belongsTo(GroupCommodity::class, 'gc_id', 'id');
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    /**
     * 处理拼团中
     * @param $now
     * @throws
     */
    public static function finishCollage($id)
    {
        $Group = new Group();
        $Group->setCollage(date("Y-m-d H:i:s", time()), 0, $id);
    }

    /**
     * @param $oc_id
     * @param $user_id
     * @throws
     */
    public static function createCollage($oc_id, $user_id)
    {
        $oc = Db::name('order_commodity')->find($oc_id);
        $mall_id = $oc['mall_id'];
        $gc_id = explode(',', $oc['gc_id']);
        $oc['gc_id'] = $gc_id[0];
        $gc = Db::name('group_commodity')->find($oc['gc_id']);
        $success_num = json_decode($gc['success_num'], true);
        if (is_array($success_num) && isset($gc_id[1])) {
            $success_num = $success_num[$gc_id[1]];
        }
        // 团长
        if ($oc['collage_id'] == 0) {
            $end_time = date('Y-m-d H:i:s', strtotime('+'.$gc['limit_time'].' minute'));
            if ($end_time >= $gc['end_time']) {
                $end_time = $gc['end_time'];
            }
            $collage_id = Db::name('collage')->insertGetId([
                'mall_id' => $mall_id,
                'gc_id' => $oc['gc_id'],
                'user_id' => $user_id,
                'commodity_id' => $oc['commodity_id'],
                'sku_id' => $oc['sku_id'],
                'oc_id' => $oc['id'],
                'status' => 1,
                'end_time' => $end_time,
                'create_time' => date("Y-m-d H:i:s"),
                'success_num' => $success_num - 1
            ]);
            Db::name('order_commodity')->where('id', $oc_id)->update(['collage_id' => $collage_id]);
        } else {
            self::isFinish($oc['collage_id']);
            // 团员
            $collageItem_id = Db::name('collage_item')->insertGetId([
                'mall_id' => $mall_id,
                'gc_id' => $oc['gc_id'],
                'collage_id' => $oc['collage_id'],
                'user_id' => $user_id,
                'commodity_id' => $oc['commodity_id'],
                'sku_id' => $oc['sku_id'],
                'create_time' => date("Y-m-d H:i:s"),
                'oc_id' => $oc['id']
            ]);
            Db::name('collage')->where('id', $oc['collage_id'])->inc("num")->save();
            $collage = Db::name('collage')->find($oc['collage_id']);
            if ($collage['success_num'] == $collage['num']) {
                Db::name('collage')->where('id', $oc['collage_id'])->update(['status' => 2]);
            }
            Db::name('order_commodity')->where('id', $oc_id)->update(['collage_item_id' => $collageItem_id]);
        }
    }
    /**
     * @param int $id
     * @throws
     */
    private static function isFinish($id)
    {
        $now = date("Y-m-d H:i:s", time());
        $collage = Db::name('collage')->find($id);
        if ($collage['end_time'] < $now || $collage['status'] != 1) {
            throw new Exception("该团已截止！", HTTP_NOTACCEPT);
        }
        $count = Db::name('collage_item')->where('collage_id', $id)->count('id');
        if ($count >= $collage['success_num']) {
            throw new Exception("该团已满！", HTTP_NOTACCEPT);
        }
    }
}
